package common

import (
	"fmt"
	"github.com/go-redis/redis/v8"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

func GetMySQLFromConsul() (db *gorm.DB, err error) {
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second,
			LogLevel:      logger.Info,
			Colorful:      true,
		},
	)
	str := ConsulSetting.vp.GetString("mysql.user") + ":" + ConsulSetting.vp.GetString("mysql.pwd") + "@tcp(" + ConsulSetting.vp.GetString("mysql.host") + ":" + ConsulSetting.vp.GetString("mysql.port") + ")/" + ConsulSetting.vp.GetString("mysql.databases") + "?charset=utf8mb4&parseTime=True&loc=Local"
	log.Println("dsn:", str)
	db, errr := gorm.Open(mysql.Open(str), &gorm.Config{Logger: newLogger})
	if errr != nil {
		log.Println("db err :", errr)
	}
	return db, nil
}

func GetRedisFromConsul() (*redis.Client, error) {
	red := redis.NewClient(&redis.Options{
		Addr:         ConsulSetting.vp.GetString("redis.addr"),
		Password:     ConsulSetting.vp.GetString("redis.password"),
		DB:           ConsulSetting.vp.GetInt("redis.DB"),
		PoolSize:     ConsulSetting.vp.GetInt("redis.poolSize"),
		MinIdleConns: ConsulSetting.vp.GetInt("redis.minIdleConn"),
	})
	log.Println("red:", ConsulSetting.vp.GetString("redis.addr"))
	// 集群
	clusterClients := redis.NewClusterClient(
		&redis.ClusterOptions{
			Addrs: []string{"192.168.100.131:6380", "192.168.100.131:6381", "192.168.100.131:6382"},
		})
	fmt.Println(clusterClients)
	return red, nil
}
